/**
 * Created by hjqi on 2016/8/27.
 */

var _static_handle = undefined;
var logger = require('../log4js/log4js').logger('system');
var myRet = require('../common/common').myReturn;
var clusterInfoMap = {};
var libK8s = require('./kubernetes');
var K8s = require('k8s');
var config = require('../config/config').config;
var clusterMetaInfoDB = require('../../db/clusterMetaInfoDB');
var clusterInfoDB = new clusterMetaInfoDB();

exports.getK8s = getK8s;
exports.setK8sHandlerNodeIP = setK8sHandlerNodeIP;
/**
 * 获取cluster中k8s的Api-server访问对象
 * @param cluster_id
 * @returns {Promise}
 */
function getK8s(cluster_id){

    return new Promise(function (resolve, reject) {

        if (cluster_id === undefined || cluster_id === null|| cluster_id === "")
            cluster_id = 'default';

        if (clusterInfoMap[cluster_id] === undefined) {

            logger.info('create k8s cluster [' + cluster_id + ']');
            var _clusterinfo = {};
            if(cluster_id === 'default'){
                _clusterinfo.clusterId = 'default';
                _clusterinfo.name = 'default';
                _clusterinfo.host = config.kubernetes.host;
                _clusterinfo.port = config.kubernetes.port;
                _clusterinfo.IPs = [config.kubernetes.host];
                clusterInfoMap[cluster_id] = new libK8s(_clusterinfo);

                //return k8s object not change temporarily
                resolve(clusterInfoMap[cluster_id]);
            }else{
                loadClusterInfo(cluster_id).then(function(clusterInfo){
                    if(clusterInfo !== {}){
                        logger.info("k8s load cluster info :"+JSON.stringify(clusterInfo));
                        _clusterinfo = clusterInfo;
                        _clusterinfo.host = cluster_id+'.'+config.tunnel.domain;
                        _clusterinfo.port = config.tunnel.port;
                        _clusterinfo.IPs = getClusterIPs(clusterInfo);
                        clusterInfoMap[cluster_id] = new libK8s(_clusterinfo);
                        resolve(clusterInfoMap[cluster_id]);
                    }else{
                        var _retmsg = "k8s can't load cluster info ["+cluster_id+"]";
                        logger.info(_retmsg);
                        reject(myRet(false,_retmsg));
                    }
                }).catch(function(err){
                    reject(err);
                });
            }
        }else{
            //return k8s object not change temporarily
            resolve(clusterInfoMap[cluster_id]);
        }

    });
}
/**
 * 查询集群中的机器信息
 * @param id
 * @returns {Promise}
 */
function loadClusterInfo(id){
    return new Promise(function (resolve, reject) {
        clusterInfoDB.getWithParam(null, {clusterId:id}, function (err,rets) {
            if (err) {
                var _retmsg = "k8s load cluster info happened error"+err.message;
                logger.error(_retmsg);
                reject(myRet(false,_retmsg));
            } else {
                var _ret = {};
                if(rets.length > 0){
                    //var _cluster = rets[0];
                    _ret =  rets[0];
                }
                //for internal return
                resolve(_ret);
            }
        });
    });
}
/**
 * 获取集群信息中的kubernetes生成的虚拟ip地址（host&externalIp）
 * @param cluster clusterInfo
 * @returns {Array}
 */
function getClusterIPs(cluster){
    var _ret = [];
    var _nodes = cluster.nodes;
    for(var id in _nodes){
        _ret.push(_nodes[id].host);
        if(_nodes[id].externalIp !== undefined)
            _ret.push(_nodes[id].externalIp);
    }
    return _ret;
}


/**
 * 检查缓存中是否有指定clusterId的集群信息
 * 此方法对于之前创建过的服务，暂时不更新新增节点的ip信息在对外访问里
 * @param cluster node info
 * @returns {null}
 */
function setK8sHandlerNodeIP(clusterNodeInfo){

    var cluster_id = clusterNodeInfo.clusterId;
    var ip = clusterNodeInfo.host;
    var _k8s = clusterInfoMap[cluster_id];
    if (_k8s !== undefined) {
        if(_k8s.IPs.indexOf(ip) === -1)
            _k8s.IPs.push(ip);
    }
}